# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import csv
import os.path
import pymongo
from scrapy.item import Item

class MoviePipeline(object):
    def process_item(self, item, spider):
        isNew = os.path.isfile('imdbtop250.csv')
        with open('imdbtop250.csv', 'a') as csvfile:
            fieldnames = ['name', 'url', 'director', 'writer', 'actor']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            if False == isNew:
                writer.writeheader()
            writer.writerow(item)



class MovieMongoPipeline(object):
    client = None
    db = None

    def open_spider(self, spider):
        self.client = pymongo.MongoClient('mongo', 27017)
        self.db = self.client[spider.name]

    def close_spider(self, spider):
        if None != self.client:
            self.client.close()

    def process_item(self, item, spider):
        collection = self.db[spider.name]
        post = dict(item) if isinstance(item, Item) else item
        collection.insert_one(post)
        return item
